# -*- coding: utf-8 -*- 
import threading
import time

from Util.util import checkACC


class rx510Thread(threading.Thread):
    def __init__(self, StateCtrl):
        super(rx510Thread, self).__init__()
        self.Ctrl = StateCtrl
        self.__flag = threading.Event()  # 用于暂停线程的标识
        self.__flag.set()  # 设置为True
        self.__running = threading.Event()  # 用于停止线程的标识
        self.__running.set()  # 将running设置为True
        self.FrameHeader = [0xA5]  # 帧头
        self.FrameLength = 40  # 定帧帧长
        pass

    def run(self):
        while self.Ctrl.Ser.isOpen() and self.__running.isSet():
            time.sleep(0.005)
            self.__flag.wait()
            if self.Ctrl.Ser.isOpen():
                if self.Ctrl.Ser.inWaiting():
                    frames = list(self.Ctrl.Ser.read(self.FrameHeader.__len__()))
                    if frames == self.FrameHeader:
                        FrameData = list(self.Ctrl.Ser.read(12))
                        FrameData.insert(0, frames[0])
                        AccCheck = checkACC(FrameData[:12])
                        if AccCheck == FrameData[12]:  # 校验和正确
                            self.Ctrl.OnReceiveData(FrameData)
                            pass
                        else:
                            # print(u'校验和错误!')
                            # print(FrameData)
                            pass



    def pause(self):
        self.__flag.clear()  # 设置为False, 让线程阻塞

    def resume(self):
        self.__flag.set()  # 设置为True, 让线程停止阻塞

    def stop(self):
        self.__flag.set()  # 将线程从暂停状态恢复, 如何已经暂停的话
        self.__running.clear()  # 设置为False
